package org.example.controller;

import org.example.domain.DeviceFaxNumber;
import org.example.dao.DeviceFaxNumberMapper;
import org.example.service.JwtTokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/app")
public class UserController {

    @Autowired
    private JwtTokenManager jwtTokenManager;
    @Autowired
    private DeviceFaxNumberMapper deviceFaxNumberMapper;

    // 游客登录接口
    @PostMapping("/appLogin")
    public Map<String, Object> appLogin(@RequestBody Map<String, String> request) {

        String deviceId = request.get("deviceId");
        if (deviceId == null || deviceId.isEmpty()) {
            throw new IllegalArgumentException("deviceId不能为空");
        }
        // 生成JWT Token
        String token = jwtTokenManager.generateToken(deviceId);

        // 返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("expiresIn", jwtTokenManager.getExpireMs() / 1000); // 秒为单位
        result.put("tokenType", "Bearer");
        return result;
    }

    // 获取当前用户信息
    @GetMapping("/info")
    public Map<String, Object> getUserInfo(@RequestHeader(name = "Authorization") String authHeader) {
        String deviceId = jwtTokenManager.validateTokenAndGetDeviceId(authHeader);

        // 构建返回用户信息
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("deviceId", deviceId);

        DeviceFaxNumber existingRecord = this.deviceFaxNumberMapper.findByDeviceID(deviceId);

        if (existingRecord == null) {
            DeviceFaxNumber newRecord = new DeviceFaxNumber();
            newRecord.setDeviceid(deviceId);
            long num = System.currentTimeMillis() % Integer.MAX_VALUE;
            newRecord.setId((int) num);
            newRecord.setNickname("guest_" + String.valueOf(num).substring(6));
            this.deviceFaxNumberMapper.insertDeviceFaxNumber(newRecord);
            existingRecord = newRecord;
        }
        userInfo.put("id", existingRecord.getId());
        userInfo.put("nickName", existingRecord.getNickname());

        return userInfo;
    }

    @PostMapping("user/update-info")
    public Map<String, Object> userUpdateInfo(@RequestHeader(name = "Authorization") String authHeader,
                                              @RequestBody Map<String, String> request) {
        try {
            String deviceId = jwtTokenManager.validateTokenAndGetDeviceId(authHeader);


            // 构建返回用户信息
            Map<String, Object> resultInfo = new HashMap<>();

            // 1. 查询是否存在该deviceId的记录
            DeviceFaxNumber existingRecord = this.deviceFaxNumberMapper.findByDeviceID(deviceId);

            if (existingRecord != null) {
                // 2. 如果存在,填充userInfo信息
                System.out.println("ID: " + existingRecord.getId());
                DeviceFaxNumber newRecord = new DeviceFaxNumber();
                newRecord.setDeviceid(deviceId);
                newRecord.setName(request.get("name"));
                newRecord.setEmail(request.get("email"));
                // 校验Email不为空
                newRecord.setPhone(request.get("phone"));

                this.deviceFaxNumberMapper.updateFaxNumberByUserInfo(newRecord);
            } else {
                // 3. 如果不存在，创建新记录，当前时间作为id
                System.out.println("Record Exists");
                DeviceFaxNumber newRecord = new DeviceFaxNumber();
                newRecord.setDeviceid(deviceId);
                long num = System.currentTimeMillis() % Integer.MAX_VALUE;
                newRecord.setId((int) num);
                newRecord.setNickname("guest_" + String.valueOf(num).substring(6));

                newRecord.setName(request.get("name"));
                newRecord.setEmail(request.get("email"));
                // 校验Email不为空
                newRecord.setPhone(request.get("phone"));

                System.out.println("begin to insert");
                this.deviceFaxNumberMapper.insertFaxNumberByUserInfo(newRecord);
            }
            resultInfo.put("code", 200);
            resultInfo.put("message", "success");
            return resultInfo;
        } catch (Exception e) {
            throw new RuntimeException("无效的token", e);
        }
    }

}
